package com.quasar.hpatient.view.personal.register;

import android.content.Intent;
import android.util.Log;
import android.view.MenuItem;

import com.ada.adapter.PagerAdapter;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.HyphenateException;
import com.quasar.hpatient.MainAppliaction;
import com.quasar.hpatient.R;
import com.quasar.hpatient.base.BaseActivity;
import com.quasar.hpatient.model.httpmodel.DataHeadResult;
import com.quasar.hpatient.model.httpmodel.DataStateResult;
import com.quasar.hpatient.model.medicalmodel.PatientInfoData;
import com.quasar.hpatient.model.operationmodel.AccountInfo;
import com.quasar.hpatient.network.RetrofitConnection;
import com.quasar.hpatient.onInterface.viewInterface.UiInterface;
import com.quasar.hpatient.utils.MyViewPager;
import com.quasar.hpatient.view.MainActivity_;
import com.quasar.hpatient.view.personal.register.registerFragment.RegisterAddressFragment_;
import com.quasar.hpatient.view.personal.register.registerFragment.RegisterBirthFragment_;
import com.quasar.hpatient.view.personal.register.registerFragment.RegisterBloodFragment_;
import com.quasar.hpatient.view.personal.register.registerFragment.RegisterHospitalFragment_;
import com.quasar.hpatient.view.personal.register.registerFragment.RegisterNameFragment_;
import com.quasar.hpatient.view.personal.register.registerFragment.RegisterOperationDateFragment_;
import com.quasar.hpatient.view.personal.register.registerFragment.RegisterOrganFragment_;
import com.quasar.hpatient.view.personal.register.registerFragment.RegisterSexFragment_;
import com.quasar.hpatient.widget.WechatTab;
import com.vise.log.ViseLog;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.StringArrayRes;

import java.util.Map;
import java.util.Random;

import chatui.DemoHelper;
import chatui.cacha.UserCacheManager;
import chatui.db.DemoDBManager;
import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * 注册时用户资料完善
 */
@EActivity(R.layout.activity_register_edit)
public class RegisterEditActivity extends BaseActivity implements UiInterface<DataStateResult> {


    @StringArrayRes
    String[] register_tabs;
    private PagerAdapter adapter;
    @ViewById(R.id.pagerFragmentProgram)
    static MyViewPager pager;
    @ViewById
    WechatTab tabs;

    String userCode= MainAppliaction.getInstance().getUserCode();
    PatientInfoData patient= MainAppliaction.getInstance().getPatient();
    Map<String, String> map = MainAppliaction.getInstance().MsgList();

    @AfterViews
    void init(){
        initView();
        initData();
    }


    @Override
    protected void initView() {
        initToolbar();
    }

    @Override
    protected void initData() {

        adapter = new PagerAdapter(getSupportFragmentManager());
        adapter.add(register_tabs[0], RegisterNameFragment_.builder().patient(patient).build());//姓名
        adapter.add(register_tabs[1], RegisterSexFragment_.builder().patient(patient).build());//性别
        adapter.add(register_tabs[2], RegisterBirthFragment_.builder().patient(patient).build());//出生日期
        adapter.add(register_tabs[3], RegisterAddressFragment_.builder().patient(patient).build());//联系地址
        adapter.add(register_tabs[4], RegisterBloodFragment_.builder().patient(patient).build());//血型
        adapter.add(register_tabs[5], RegisterOrganFragment_.builder().patient(patient).build());//器官来源
        adapter.add(register_tabs[6], RegisterOperationDateFragment_.builder().patient(patient).build());//手术时间
        adapter.add(register_tabs[7], RegisterHospitalFragment_.builder().patient(patient).build());//手术医院
        pager.setAdapter(adapter);

        pager.setPageMargin(0);
        tabs.setViewPager(pager);
        pager.setSaveEnabled(false);//禁止viewPager滑动
    }

    public static void ViewPage(int page){
        pager.setCurrentItem(page);
    }



//
//    //检测返回按钮
//    @Override
//    public boolean onOptionsItemSelected(MenuItem item) {
//        switch (item.getItemId()) {
//            case android.R.id.home:
//                ViseLog.d("点击了返回按钮");
//                PostUserinfo();
//                break;
//        }
//        return super.onOptionsItemSelected(item);
//    }
//
//    @Override
//    public void onBackPressed() {
//        ViseLog.d("发送通知更新界面");
//        PostUserinfo();
//    }


    //修改用户信息成功后重新获取个人信息
    public void PostUserinfo(){
        RetrofitConnection.getRoutineApi()
                .UserInformation(userCode,patient.getPhone())
                .observeOn(Schedulers.io())
                .subscribeOn(Schedulers.io())
                .doOnNext(new Consumer<DataHeadResult<PatientInfoData>>() {
                    @Override
                    public void accept(DataHeadResult<PatientInfoData> patientInfoDataDataHeadResult) throws Exception {
                        if(!patientInfoDataDataHeadResult.getMsgCode().equals("0x00000000")){
                            throw new RuntimeException(map.get(patientInfoDataDataHeadResult.getMsgCode()));
                        }
                    }
                })
                .subscribe(new Observer<DataHeadResult<PatientInfoData>>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull DataHeadResult<PatientInfoData> patientInfoDataDataHeadResult) {
                        ViseLog.d("onNext"+patientInfoDataDataHeadResult.getData());
                        AccountInfo.saveAccount(RegisterEditActivity.this, patientInfoDataDataHeadResult.getData());
                        logChat(patientInfoDataDataHeadResult.getData(),patientInfoDataDataHeadResult.getData().getBmobUserName());
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        ViseLog.d("onError"+e.getMessage());
                        dessDialog();
                    }

                    @Override
                    public void onComplete() {
                        ViseLog.d("onComplete");
                        dessDialog();
                    }
                });
    }

    /**
     * 登陆环信
     * @param userName 账号   密码默认为 123456
     */
    public void logChat(final PatientInfoData patientInfoData, final String userName){
        // After logout，the DemoDB may still be accessed due to async callback, so the DemoDB will be re-opened again.
        // close it before login to make sure DemoDB not overlap
        EMClient.getInstance().logout(true); //登陆前先退出，保证登陆成功！
        DemoDBManager.getInstance().closeDB();

        // reset current user name before login
        DemoHelper.getInstance().setCurrentUserName(userName);
        EMClient.getInstance().login(userName,"a123456", new EMCallBack() {

            @Override
            public void onSuccess() {

                Random random=new Random();
                // 登录成功，将用户的昵称头像缓存在本地
                String userId = EMClient.getInstance().getCurrentUser();// 用户环信ID
                //名称
                String nickName;
                if(patientInfoData.getRealName()!=null){
                    nickName=patientInfoData.getRealName();
                }else{
                    nickName=userName;
                }

                String avatarUrl = "";
                if(patientInfoData.getCover()!=null){
                    avatarUrl = RetrofitConnection.PHOTOURL+patientInfoData.getCover();
                }


                UserCacheManager.save(userId, nickName, avatarUrl);

                // ** manually load all local groups and conversation
                EMClient.getInstance().groupManager().loadAllGroups();
                EMClient.getInstance().chatManager().loadAllConversations();

                String nick = "";
                try {
                    nick = EMClient.getInstance().pushManager().getPushConfigsFromServer().getDisplayNickname();
                } catch (HyphenateException e) {
                    e.printStackTrace();
                }

                // update current user's display name for APNs
                boolean updatenick = EMClient.getInstance().pushManager().updatePushNickname(nickName);
                if (!updatenick) {
                    Log.e("LoginActivity", "update current user nick fail");
                }

                DemoHelper.getInstance().getUserProfileManager().asyncGetCurrentUserInfo();

                Intent intent = new Intent(RegisterEditActivity.this,
                        MainActivity_.class);
                startActivity(intent);
                dessDialog();
            }

            @Override
            public void onProgress(int progress, String status) {
                ViseLog.d("login: onProgress"+status);
                dessDialog();
            }

            @Override
            public void onError(final int code, final String message) {
                ViseLog.d("login: onError:"+code+"+++"+message);
                dessDialog();
            }
        });

    }

    @Override
    public void onViewSuccess(DataStateResult data) {

    }

    @Override
    public void onViewError(String msg) {

    }

    @Override
    public void onViewRefreshUI() {

    }
}
